package com.kcht.itsed.mws.subscribescheduler.biz;

import com.kcht.itsed.mws.commmodel.SubscribedReport;
import com.kcht.itsed.mws.subscribescheduler.facade.ISubscriberLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import java.io.ByteArrayInputStream;
import java.util.List;

/**
 * 普通订阅类型的Topic侦听器（普通S订阅的File/Http/Ftp等）
 * 关联java:/jms/topic/SpecReportSubscriptionTopic
 * 所有HTTP订阅通过此处分派报告发送
 * 
 * 和AleFramework模块的ISubscriptionSender接口是好基友
 * 
 * @author 张文硕
 *
 */
@Component
@Slf4j
public class CommonSubscriberProcessorMdb {

	@Autowired
	private ISubscriberLoader subscriberLoader;
	@Autowired
	IConcreteReportSenderFactory reportSenderFactory;
	
	@JmsListener(destination = "ALE订阅者的报告" ,containerFactory = "topicFactory")
	public void onMessage(Message msg) {
		try {
			SubscribedReport report = (SubscribedReport)((ObjectMessage)msg).getObject();
			sendToAllRelatedSubscribers(report);
		} catch (JMSException e) {
			log.error("订阅者获取消息异常",e);
		}
	}

	private void sendToAllRelatedSubscribers(SubscribedReport report) {
		List<String> subs = subscriberLoader.loadSubscribersOfSpec(report.getSpecType(),report.getSpecName());
		byte[] reportBytes = report.getReportXml().getBytes();
		if(subs!=null)subs.forEach(url->
			reportSenderFactory.fetchSender(url).send(new ByteArrayInputStream(reportBytes))
		);
	}

}
